package com.warm.pump.module.sys.controller;


import com.warm.pump.frame.gen.util.OutJson;
import com.warm.pump.frame.shiro.ShiroUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

/**
 * 登录相关
 */
@Controller
public class SysLoginController {




	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public OutJson login(String username, String password, String captcha) throws IOException {
//		String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
//		if (!captcha.equalsIgnoreCase(kaptcha)) {
//			return OutJson.error("验证码不正确");
//		}

		try {
			Subject subject = ShiroUtils.getSubject();
			// sha256加密
			password = new Sha256Hash(password).toHex();
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			subject.login(token);
		} catch (UnknownAccountException e) {
			return OutJson.error(e.getMessage());
		} catch (IncorrectCredentialsException e) {
			return OutJson.error(e.getMessage());
		} catch (LockedAccountException e) {
			return OutJson.error(e.getMessage());
		} catch (AuthenticationException e) {
			return OutJson.error("账户验证失败");
		}

		return OutJson.ok();
	}

	/**
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login.html";
	}



}
